using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[RequireComponent (typeof (NetworkView))]
public class RPCListener<E> : MonoBehaviour where E : CallEvent, new() {
	private class Impl : Listener<int, E> {}
	private Impl listener = new Impl();
	
	// Add a listener on a specific channel.
	public void add(int channel, System.Action<E> l) {
		listener.add(channel, l);
	}
	
	// Notify listeners on a specific channel.
	public void notify(int channel, E ev) {
		Debug.Log (ev);
		
		listener.notify(channel, ev);
		networkView.RPC(
			"rpcNotify", 
			RPCMode.OthersBuffered, 
			channel, 
			ev.toJSON()
		);
	}
	
	// Calls the notify function on the corresponding listener in all
	// other clients.
	[RPC]
	private void rpcNotify(int channel, string json) {
		listener.notify(channel, createFromJSON(json));
	}
	
	// Finds the event with the specified id or null (the default value)
	// if it does not exist in the scene.
	private E createFromJSON(string json) {
		E ev = new E();
		ev.fromJSON(json);
		return ev;
	}
}
